//
//  BVSearchShopsViewController.m
//  BuyVegetables
//
//  Created by 叶思超 on 15/10/14.
//  Copyright (c) 2015年 叶思超. All rights reserved.
//

#import "BVSearchShopsViewController.h"
#import "BVConst.h"
#import "UIView+Extension.h"
#import "BVSearchDetailShopsViewController.h"
#import "HttpTool.h"
#import "UIView+Extension.h"
#import "BVSearchInfoCell.h"

@interface BVSearchShopsViewController () <UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, BVSearchDetailShopsViewControllerDelegate,UIGestureRecognizerDelegate>
/**
 *  创建tableView
 */
@property (nonatomic, strong) UITableView *tableView;
/**
 *  搜索框
 */
@property (nonatomic, strong) UITextField *searchField;
/**
 *  存储历史搜索记录
 */
@property (nonatomic, strong) NSMutableArray *oldInfo;
@end

@implementation BVSearchShopsViewController

- (NSMutableArray *)oldInfo {
    if (!_oldInfo) {
        _oldInfo = [[NSMutableArray alloc]init];
    }
    return _oldInfo;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.frame = CGRectMake(0, 64, BVScreenW, BVScreenH - 64 - 216 - 40);
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.bounces = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeybord)];
        tap.delegate = self;
        [_tableView addGestureRecognizer:tap];
        
        // tableview头部
        UIView *headerView = [[UIView alloc] init];
        headerView.frame = CGRectMake(0, 0, BVScreenW, 40);
        headerView.backgroundColor = BVColor(248, 248, 248);
        _tableView.tableHeaderView = headerView;
        
        // 头部标签
        UILabel *searchLable = [[UILabel alloc] init];
        searchLable.frame = CGRectMake(10, 0, BVScreenW - 10, 40);
        searchLable.font = [UIFont systemFontOfSize:15];
        searchLable.text = @"搜索历史";
        [headerView addSubview:searchLable];
        
        // tableview尾部
        UIView *footerView = [[UIView alloc] init];
        footerView.frame = CGRectMake(0, 0, BVScreenW, 40);
        footerView.backgroundColor = BVColor(232, 232, 230);
        _tableView.tableFooterView = footerView;
        
        // 清除历史按钮
        UIButton *clearButton = [[UIButton alloc] init];
        clearButton.frame = CGRectMake(0, 0, BVScreenW, 40);
        clearButton.backgroundColor = [UIColor clearColor];
        [clearButton setTitle:@"清除搜索历史" forState:UIControlStateNormal];
        [clearButton setTitleColor:BVBaseOrangeColor forState:UIControlStateNormal];
        clearButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [clearButton addTarget:self action:@selector(clearButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:clearButton];
    }
    return _tableView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.searchField becomeFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置导航栏
    [self setupNav];
}
#pragma mark  解决手势冲突
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//如果当前是tableView
        //做自己想做的事
        return NO;
    }
    return YES;
}

#pragma mark -- 设置导航栏
- (void)setupNav {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backClick)];
    
    UIButton *searchButton = [[UIButton alloc] init];
    searchButton.frame = CGRectMake(BVScreenW - 50, 35, 50, 35);
    searchButton.backgroundColor = BVColor(68, 69, 70);
    [searchButton setImage:[UIImage imageNamed:@"sy_search"] forState:UIControlStateNormal];
    searchButton.layer.cornerRadius = 4;
    searchButton.layer.masksToBounds = YES;
    searchButton.adjustsImageWhenHighlighted = NO;
    [searchButton addTarget:self action:@selector(searchShopsClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:searchButton];
    
    // 搜索框
    self.searchField = [[UITextField alloc] init];
    self.searchField.frame = CGRectMake(44, 35, searchButton.x - 44 - 10, 35);
    self.searchField.placeholder = @"请输入菜品名称";
    self.searchField.backgroundColor = [UIColor clearColor];
    [self.searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.searchField setValue:[UIFont boldSystemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    self.searchField.layer.cornerRadius = 4;
    self.searchField.layer.masksToBounds = YES;
    self.searchField.delegate = self;
    self.searchField.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = self.searchField;
}

#pragma mark -- UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *array = [defaults arrayForKey:@"oldInfo"];
    
    if (array.count != 0) {
        // 刷新tableView
        [self.tableView reloadData];
    }
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *array = [defaults arrayForKey:@"oldInfo"];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *array = [defaults arrayForKey:@"oldInfo"];
    // 创建cell
    BVSearchInfoCell *cell   = [BVSearchInfoCell cellWithTableView:tableView];
    cell.name  = array[indexPath.row];

    return cell;
}

#pragma mark -- UITableviewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 隐藏键盘
    [self.searchField resignFirstResponder];
    
    BVSearchDetailShopsViewController *searchDetailVC = [[BVSearchDetailShopsViewController alloc] init];
    searchDetailVC.delegate = self;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *array = [defaults arrayForKey:@"oldInfo"];
    searchDetailVC.titleStr = array[indexPath.row];
    ROOTNAVPUSH(searchDetailVC, YES);
}

#pragma mark -- 搜索
- (void)searchShopsClick:(UIButton *)button {
    // 没有输入内容
    if (self.searchField.text.length == 0) return;
        // 隐藏键盘
    [self.searchField resignFirstResponder];
    
    // 判断当前搜索商品是否在历史搜索中
    [self correctInfo];
    
    BVSearchDetailShopsViewController *searchDetailShopsVC = [[BVSearchDetailShopsViewController alloc] init];
    searchDetailShopsVC.titleStr = self.searchField.text;
    searchDetailShopsVC.delegate = self;
    ROOTNAVPUSH(searchDetailShopsVC, YES);
}

#pragma mark -- 判断信息
- (void)correctInfo {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray * mArr = [[defaults objectForKey:@"oldInfo"] mutableCopy];
    if (![mArr containsObject:self.searchField.text]) {
        [mArr addObject:self.searchField.text];
        [defaults setObject:mArr forKey:@"oldInfo"];
        [defaults synchronize];
    }
}

#pragma mark -- 清空缓存
- (void)clearButtonClick {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [self.oldInfo removeAllObjects];
    [defaults setObject:self.oldInfo forKey:@"oldInfo"];
    
    // 刷新tableview
    self.tableView.hidden = YES;
}

#pragma mark -- 设置背景图片
- (void)setupBg {
    UIImageView *bgImage = [[UIImageView alloc] init];
    bgImage.frame = self.view.bounds;
    bgImage.userInteractionEnabled = YES;
    bgImage.image = [UIImage imageNamed:@"bg"];
    [self.view addSubview:bgImage];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKeybord)];
    bgImage.userInteractionEnabled = YES;
    [bgImage addGestureRecognizer:tap];
}

#pragma mark -- 返回
- (void)backClick {
    ROOTNAVPOP
    [self.searchField resignFirstResponder];
}

#pragma mark -- 隐藏键盘
- (void)hideKeybord {
    [self.searchField resignFirstResponder];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.searchField resignFirstResponder];
}

#pragma mark -- BVSearchDetailShopsViewControllerDelegate
- (void)searchDetailShopsDidFinish:(BVSearchDetailShopsViewController *)searchDetailShops {
    // 显示tableview
    self.tableView.hidden = NO;
    // 刷新tableview
    [self.tableView reloadData];
}

#pragma mark -- UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
    [self searchShopsClick:nil];
}
@end
